const fs = require('fs');
const { pool } = require('../../db/index');
const Router = require('koa-router');
// 引入 path 模块
const path = require('path');

const router = new Router();

// 获取所有字帖
router.get('/api/allBooks', async (ctx) => {
    try {
        const [rows] = await pool.execute('SELECT * FROM all_books');
        if (rows.length > 0) {
            const responses = rows.map(item => {
                const relativePath = item.cover_image.replace(/^.*?imgs\//, '').replace(/\\/g, '/');
                const fullImageUrl = `${module.exports.serverUrl}/${relativePath}`;
                return {
                    id: item.id,
                    name: item.name,
                    image_url: fullImageUrl,
                    author: item.author,
                    authorId: item.authorId,
                };
            });
            ctx.body = responses;
        } else {
            ctx.status = 404;
            ctx.body = { error: 'file not found' };
        }
    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: '获取所有字帖失败' };
    }
});

// 获取字帖详情
router.get('/api/book_detail/:id', async (ctx) => {
    try {
        const id = ctx.params.id;
        console.log('id', id);
        // 执行 SQL 查询，通过 id 获取书法家的全部信息
        const [rows] = await pool.execute('SELECT * FROM all_books WHERE id = ?', [id]);
        if (rows.length) {
            // 文件夹路径
            const relativePath = rows[0].book_image_url.replace(/\//g, '\\');
            console.log('relativePath', relativePath);

            const baseUrl = path.join(module.exports.localUrl, rows[0].book_image_url);
            console.log('baseUrl', baseUrl);

            // 读取文件夹内容
            const files = await fs.promises.readdir(baseUrl);

            // 过滤出其中的图片
            const imageFiles = files.filter(file => {
                const ext = path.extname(file).toLowerCase();
                return ['.jpg', '.jpeg', '.png', '.gif', '.webp'].includes(ext);
            });

            // 最终的图片 url 数组，将本地路径替换为服务器地址
            const imagePaths = imageFiles.map(file => {
                // 拼接相对路径
                const localImagePath = path.join(relativePath, file);
                // 将反斜杠替换为正斜杠，以符合 URL 规范
                const relativeUrl = localImagePath.replace(/\\/g, '/');
                // 拼接服务器地址和相对路径
                return `${module.exports.serverUrl}/${relativeUrl}`;
            });

            // 按文件名中的数字排序
            imagePaths.sort((a, b) => {
                // 提取文件名
                const fileNameA = a.split('/').pop();
                const fileNameB = b.split('/').pop();
                // 提取文件名中的编号部分
                const numPartA = fileNameA.match(/\d+/);
                const numPartB = fileNameB.match(/\d+/);
                if (numPartA && numPartB) {
                    const numA = parseInt(numPartA[0], 10);
                    const numB = parseInt(numPartB[0], 10);
                    return numA - numB;
                }
                return 0;
            });

            console.log('imagePaths', imagePaths);

            ctx.body = {
                id: rows[0].id,
                name: rows[0].name,
                author: rows[0].author,
                image_url: imagePaths
            };
        }
    } catch (error) {
        console.error('数据库查询出错:', error);
        ctx.status = 500;
        ctx.body = { error: '服务器内部错误' };
    }
});



module.exports = router;